﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace TrackClasses
{
    public static class WritableBitmapExtender
    {

        public static void SetPixel(
            this WriteableBitmap wbm,
            int x, int y, Color c)
        {
            if (y > wbm.PixelHeight - 1 ||
                x > wbm.PixelWidth - 1) return;
            if (y < 0 || x < 0) return;
            wbm.Pixels[y*wbm.PixelWidth + x] =
                c.A << 24 | c.R << 16 |
                c.G << 8 | c.B;
        }

        public static Color GetPixel(this WriteableBitmap bmp, int x, int y)
        {
            var c = bmp.Pixels[y * bmp.PixelWidth + x];
            var a = (byte)(c >> 24);

            // Prevent division by zero
            int ai = a;
            if (ai == 0)
            {
                ai = 1;
            }

            // Scale inverse alpha to use cheap integer mul bit shift
            ai = ((255 << 8) / ai);
            return Color.FromArgb(a,
                                 (byte)((((c >> 16) & 0xFF) * ai) >> 8),
                                 (byte)((((c >> 8) & 0xFF) * ai) >> 8),
                                 (byte)((((c & 0xFF) * ai) >> 8)));
        }

    }

}
